import * as React from "react";
import EventsUtils from "../../utils/EventsUtils";
import CommonUtils from "../../utils/CommonUtils";
import "./index.css";

/**
 * 载入中面板
 * 通过事件触发显示
 */
export default class Loading extends React.Component{
    constructor(props){
        super(props);
        this.state = {
            loadingStyle: {}
        };
        this.show = this.show.bind(this);
        this.hidden = this.hidden.bind(this);
        this.transitionEndHandler = this.transitionEndHandler.bind(this);
    }

    render(){
        return (
            <div
                id="loading"
                className="fade"
                style={this.state.loadingStyle}
                ref={element=>this.container = element}
                onTransitionEnd={this.transitionEndHandler}
            >
            </div>
        )
    }

    /**
     * 装载完成时，添加监听器
     */
    componentDidMount(){
        EventsUtils.on(Loading.events.LOADING, this.show);
        EventsUtils.on(Loading.events.COMPLETE, this.hidden);
    }

    /**
     * 卸载时，删除监听器
     */
    componentWillUnmount(){
        EventsUtils.removeListener(Loading.events.LOADING, this.show);
        EventsUtils.removeListener(Loading.events.COMPLETE, this.hidden);
    }

    /**
     * 动画完成事件，如果是隐藏动画，则设置display为none
     */
    transitionEndHandler() {
        if(!this.container.style.opacity){
            this.setState({loadingStyle:{display: "none"}});
            this.closing = false;
        }
    }

    /**
     * 显示
     */
    show(){
        //如果已经显示，则返回
        if(this.state.display === "block" && !this.closing) return;
        this.setState({loadingStyle: {display: "block"}});
        CommonUtils.waitBrowserRender(this.container);
        this.setState({loadingStyle: {display: "block", opacity: 1}});
    }

    /**
     * 隐藏
     */
    hidden(){
        //正在关闭
        this.closing = true;
        this.setState({loadingStyle: {}});
    }
}
/**
 * 事件列表
 * @type {{LOADING: string, COMPLETE: string}}
 */
Loading.events = {
    LOADING : "leader.events.loading.loading",
    COMPLETE: "leader.events.loading.complete"
};
Object.freeze(Loading.events);
